package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Item;
import model.Member;
import utils.Utils;
import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;

public class EditItem extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		Integer idItem = WebUtils.safeGetParameterInteger(req, "idItem");
		String name = WebUtils.safeGetParameterString(req, "name");
		String description = WebUtils.safeGetParameterString(req, "description");
		Double latitude = WebUtils.safeGetParameterDouble(req, "latitude");
		Double longitude = WebUtils.safeGetParameterDouble(req, "longitude");
		String street = WebUtils.safeGetParameterString(req, "street");
		String city = WebUtils.safeGetParameterString(req, "city");
		String state = WebUtils.safeGetParameterString(req, "state");
		String country = WebUtils.safeGetParameterString(req, "country");
		String zipcode = WebUtils.safeGetParameterString(req, "zipcode");
		String phone = WebUtils.safeGetParameterString(req, "phone");
		String cellphone = WebUtils.safeGetParameterString(req, "cellphone");
		String email = WebUtils.safeGetParameterString(req, "email");
		String skype = WebUtils.safeGetParameterString(req, "skype");
		String url = WebUtils.safeGetParameterString(req, "url");
		
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		String[] idCategoryArray = req.getParameterValues("idCategory");
		
		if(idItem == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "idItem parameter is required");
			return;
		}
		
		if(Utils.isEmpty(name)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "name parameter is required");
			return;
		}
		
		if(idCategoryArray == null || idCategoryArray.length == 0){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "idCategory parameter is required");
			return;
		}		
		
		if(Utils.isEmpty(street)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "street parameter is required");
			return;
		}

		if(Utils.isEmpty(city)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "city parameter is required");
			return;
		}

		if(Utils.isEmpty(state)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "state parameter is required");
			return;
		}

		if(Utils.isEmpty(country)){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "country parameter is required");
			return;
		}
		
		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		Item item = manager.get(Item.class, idItem);
		
		if(item == null){
			resp.sendError(HttpServletResponse.SC_NOT_FOUND, "item not found");
			return;
		}		
		
		if(member == null || (!member.isSuperAdmin() && !member.getIdMember().equals(item.getIdItem()))){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
			return;	
		}
		
		Set<Category> categories = new HashSet<Category>();
		for (int i = 0; i < idCategoryArray.length; i++) {
			String idCategoryStr = idCategoryArray[i];
			Category category = new Category(new Integer(idCategoryStr));
			categories.add(category);
		}
		
		item.setCategories(categories);
		item.setName(name);
		item.setDescription(description);
		item.setLatitude(latitude);
		item.setLongitude(longitude);
		item.setStreet(street);
		item.setCity(city);
		item.setState(state);
		item.setCountry(country);
		item.setZipcode(zipcode);
		item.setPhone(phone);
		item.setCellphone(cellphone);
		item.setEmail(email);
		item.setSkype(skype);
		item.setUrl(url);		
		item.setMember(member);
		
		try{
			if(latitude == null || longitude == null){
				Lookup.lookupGeocoder().geocodeItem(item);
			}
		}catch (Exception e) {
			throw new ServletException("Exception Geocoding item", e);
		}		
		
		manager.merge(item);
		
		String outputString = "{success: true}";	
		
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/html;charset=UTF-8");
		writer.print(outputString);
		writer.close();
	}
	
	

	

}
